<?php

declare(strict_types=1);

namespace app\sys\controller;

use think\admin\Controller;
use think\admin\model\SysMessage;
use think\admin\model\SysRelation;
use think\admin\model\SysUser;
use think\admin\service\AdminService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 站内信接口
 * Class Message
 * @package app\sys\controller
 */
class Message extends Controller
{
    /**
     * 站内信管理
     * @auth true
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function page()
    {
        $query = SysMessage::mQuery();
        $query->where(['is_deleted' => 0]);
        // 数据列表搜索过滤
        $query->equal('created_by')->dateBetween('create_time');
        $query->like('subject,category');
        $query->dataScope('created_by');
        $lists = $query->order('id desc')->page();
    }

    /**
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function list()
    {
        $ids = SysRelation::mk()->where(['target_id' => AdminService::getUserId()])->where(['category' => 'DEV_MESSAGE_HAS_USER'])->column('object_id');
        $query = SysMessage::mQuery();
        $query->whereIn('id', $ids);
        // 数据列表搜索过滤
        $query->equal('status');
        $query->like('category');
        $lists = $query->order('id ASC')->page(false,false,false);
        sysoplog('用户消息管理', '用户消息分页列表获取成功');
        $this->success('数据获取成功', $lists['list']);
    }
    /**
     * 发送站内信
     * @auth true
     * @return void
     */
    public function send()
    {
        sysoplog('站内信管理', '站内信发送成功');
        SysMessage::mForm();
    }

    /**
     * 获取站内信详情
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function detail()
    {
        $id = intval($this->request->param('id'));
        if ($id) {
            $data = SysMessage::mk()->where(['is_deleted' => 0, 'status' => 0])->where(['id' => $id])->findOrEmpty();
            $receiveInfoList = [];
            $receiveList = SysRelation::mk()->where(['object_id' => $id])->where(['category' => 'DEV_MESSAGE_HAS_USER'])->select()->toArray();
            if ($receiveList) {
                foreach ($receiveList as $v) {
                    $receiveInfoList[] = [
                        'receiveUserId' => $v['targetId'],
                        'receiveUserName' => $this->_getUserName((int)$v['targetId']),
                        'read' => json_decode($v['extJson'], true)['read']
                    ];
                }
            }
            $data['receiveInfoList'] = $receiveInfoList;
            $this->success('获取成功', $data);
        } else {
            $this->error('id不存在');
        }
    }

    /**
     * 获取用户名
     * @param int $id
     * @return string
     */
    private function _getUserName(int $id): string
    {
        return SysUser::mk()->where(['id' => $id])->value('name');
    }

    /**
     * 表单处理
     * @param bool $result
     * @param array $data
     * @return void
     */
    protected function _form_result(bool $result, array $data)
    {
        if ($data['receiverIdList']) {
            SysRelation::mk()->where(['object_id' => $data['id'], 'category' => 'DEV_MESSAGE_HAS_USER'])->delete();
            $messageData = [];
            foreach ($data['receiverIdList'] as $v) {
                $messageData[] = [
                    'object_id' => $data['id'],
                    'target_id' => $v,
                    'category' => 'DEV_MESSAGE_HAS_USER',
                    'ext_json' => json_encode(['read' => false])
                ];
            }
            SysRelation::mk()->insertAll($messageData);
        }
        if ($result) {
            $this->success('发送成功！');
        }
    }

    /**
     * 删除站内信
     * @auth true
     */
    public function delete()
    {
        $messageIds = $this->request->param('id');
        SysRelation::mk()->whereIn('object_id', $messageIds)->delete();
        SysMessage::mDelete();
    }
}